<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * API Controller Class
 *
 * This class object is the super class for e-future projects
 *
 * @author    renwenxin@e-future.com.cn
 */
class API_Controller extends CI_Controller {

  public function __construct() {
    parent::__construct();

    $method = $this->router->fetch_method();

    if (isset($this->_rules) && !empty($this->_rules[$method]))
    {
        $this->load->library('form_validation');
        $this->validate($this->_rules[$method]);
    }

  }

  protected function to_api_message($status = 0, $msg = NULL, $data = NULL, $total = NULL) {
    $ret_arr = array('status' => $status);

    $plt = array('msg', 'data', 'total');

    foreach ($plt as $v) {
      if (isset($$v)) {
        $ret_arr[$v] = $$v;
      }
    }
    echo json_encode($ret_arr);
    exit();
  }

  protected function validate($rules) {
    foreach ($rules as $rule) {
      $this->form_validation->set_rules($rule[0], $this->dsr_line($rule[1]), $rule[2]);
    }
    if ($this->form_validation->run() === FALSE) {
      $errors = strip_tags(validation_errors());
      if (!$errors) {
        return $this->to_api_message(0, $this->dsr_line(array('parameter', 'not', 'exist')));
      }
      return $this->to_api_message(0, $errors);
    }
  }

  public function dsr_line($do = '', $sth = '', $result = '', $structure = 'do_sth_result') {
    return sprintf($this->line($structure), $this->array_to_str($do), $this->array_to_str($sth), $this->array_to_str($result)
    );
  }

  public function line($name) {
    $this->lang->load('common');
    $re = $this->lang->line($name);
    if(!$re)
      $re = $name;

    return $re;
  }

  private function array_to_str($arr) {
    $str = '';
    if (!is_array($arr)) {
      return $this->line($arr);
    }
    foreach ($arr as $v) {
      $str .= $this->line($v);
    }
    return $str;
  }

}

// END API_Controller class

/* End of file API_Controller.php */
/* Location: ./application/core/API_Controller.php */

